<?php

namespace app\admin\controller;

use app\admin\middleware\CheckAdmin;
use app\BaseController;
use app\common\BusinessException;
use think\facade\Db;

class Template extends BaseController
{

    public $middleware = [
        CheckAdmin::class,
    ];

    protected $noNeedLogin = ["list"];

    /**
     * 详情
     */
    public function index()
    {
        $id = $this->request->param('id');
        $template = Db::name('template')->where('id', $id)->find();
        if (!$template) {
            throw new BusinessException('模板不存在');
        }
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $template]);
    }

    /**
     * 列表
     */
    public function list()
    {
        // 查询条件

        $pageNum = $this->request->param('pageNum', 1);
        $pageSize = $this->request->param('pageSize', 10);

        $data = Db::name('template')
            ->where($where)
            ->paginate([
                'list_rows' => $pageSize,
                'page' => $pageNum,
            ]);

        return json(['code' => 200, 'msg' => '获取成功', 'data' => $data]);

    }

    /**
     * 新增
     */
    public function add()
    {
        $data = $this->request->post();
        // 校验新增参数
        $res = Db::name('template')->insert($data);
        if (!$res) {
            throw new BusinessException('新增失败');
        }
        return json(['code' => 200, 'msg' => '新增成功', 'data' => $data]);
    }

    /**
     * 编辑
     */
    public function edit()
    {
        $data = $this->request->post();
        // 校验编辑参数
        $res = Db::name('template')->where('id', $data['id'])->update($data);
        return json(['code' => 200, 'msg' => '编辑成功', 'data' => $res]);
    }

    /**
     * 删除
     */
    public function remove()
    {
        // 修改成软删除
        $data = $this->request->post();
        $data['deleteTime'] = time();
        $id = $this->request->param('id');
        $res = Db::name('template')->where('id', $id)->update($data);
        if (!$res) {
            throw new BusinessException('删除失败');
        }
        return json(['code' => 200, 'msg' => '删除成功', 'data' => $res]);
    }
    /**
     * 恢复
     */
    public function recover()
    {
        $data = $this->request->post();
        $data['deleteTime'] = 0;
        $id = $this->request->param('id');
        $res = Db::name('template')->where('id', $id)->update($data);
        if (!$res) {
            throw new BusinessException('恢复失败');
        }
        return json(['code' => 200, 'msg' => '恢复成功', 'data' => $res]);
    }

    public function changeStatus()
    {
        $id = $this->request->param('id');
        $status = $this->request->param('status');
        $res = Db::name('template')->where('id', $id)->update(['status' => $status]);
        if (!$res) {
            throw new BusinessException('修改失败');
        }
        return json(['code' => 200, 'msg' => '修改成功', 'data' => $res]);
    }

}
